using UnityEngine;
using System.Collections;

public class Toss : MonoBehaviour {

    Vector3 start;
    Vector3 velocity;

    public GameObject visual;
    public bool swipeToJump = false;

	void Start () {
        rigidbody.useGravity = true;
        visual.GetComponent<Ferr2D_Animator>().SetAnimation("fly");
	}

	void Update () {
        if (rigidbody.useGravity)
        {
            visual.transform.rotation = Quaternion.FromToRotation(Vector3.right, rigidbody.velocity);
            visual.transform.eulerAngles -= new Vector3(0, 0, 90);
        }
        
        if (Input.GetButtonDown("Fire1"))
        {
            start = Input.mousePosition;
        }
        else if (Input.GetButtonUp("Fire1"))
        {
            Ray   ray  = Camera.main.ScreenPointToRay(Input.mousePosition);
            float dist = 0;
            new Plane(-Vector3.forward, transform.position.z).Raycast(ray, out dist);

            if (swipeToJump)
                rigidbody.AddForce( (Input.mousePosition - start) * 2.1f );
            else
                rigidbody.AddForce( (ray.GetPoint(dist) - transform.position) * 100f );

            visual.GetComponent<Ferr2D_Animator>().SetAnimation("jump");
            rigidbody.useGravity = true;
        }
	}

    void OnCollisionEnter(Collision collision)
    {
        //if (collision.gameObject.isStatic)
        {
            visual.GetComponent<Ferr2D_Animator>().SetAnimation("land");
            rigidbody.useGravity = false;
            rigidbody.velocity = Vector3.zero;
            rigidbody.Sleep();

            visual.transform.rotation = Quaternion.FromToRotation(Vector3.right, collision.contacts[0].normal);

            if (visual.transform.eulerAngles.y != 0)
            {
                visual.transform.eulerAngles = new Vector3(0, 0, visual.transform.eulerAngles.z - 270);
            }
            else
            {
                visual.transform.eulerAngles = new Vector3(0, 0, visual.transform.eulerAngles.z - 90);
            }
        }
    }
}
